<template>
  <div class="event-info-container">
    <!-- 选项卡 -->
    <el-tabs v-model="activeTab" class="custom-tabs">
      <!-- 事件信息页 -->
      <el-tab-pane label="事件信息" name="event">
        <!-- 加载状态 -->
        <el-skeleton :loading="loading" animated>
          <!-- 事件表格 -->
          <el-table
            :data="eventList"
            height="400"
            border
            class="event-table"
            empty-text="暂无数据"
            v-loading="loading"
          >
            <el-table-column label="序号" type="index" width="60" align="center" />
            <el-table-column prop="事件编号" label="事件编号" width="160" align="center" />
            <el-table-column prop="事件类型" label="事件类型" width="100" align="center" />
            <el-table-column prop="事件等级" label="事件等级" width="100" align="center" />
            <el-table-column prop="发生时间" label="发生时间" width="200" align="center" />
            <el-table-column prop="发生地点" label="发生地点" align="center" />
            <el-table-column prop="车牌号" label="车牌号" width="120" align="center" />
            <el-table-column prop="驾驶员" label="驾驶员" width="110" align="center" />
            <el-table-column prop="处理状态" label="处理状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.处理状态 === '2' ? 'success' : row.处理状态 === '1' ? 'primary' : 'warning'
                  "
                  size="small"
                  class="status-tag"
                  effect="plain"
                >
                  {{ row.处理状态 === '2' ? '已处理' : row.处理状态 === '1' ? '审核中' : '未处理' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </el-tab-pane>

      <!-- 统计图页 -->
      <el-tab-pane label="统计图" name="chart">
        <div class="chart-group" v-if="activeTab === 'chart'">
          <div class="chart-card">
            <h3>事件类型分析</h3>
            <v-chart class="chart" :option="typeOption" autoresize />
          </div>
          <div class="chart-card">
            <h3>事件等级分析</h3>
            <v-chart class="chart" :option="levelOption" autoresize />
          </div>
        </div>
      </el-tab-pane>

      <!-- 热力图页 -->
      <el-tab-pane label="热力图" name="heatmap">
        <div class="heatmap-container">
          <el-switch
            v-model="isHeatmapEnabled"
            active-text="开启"
            inactive-text="关闭"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <div class="radius-size">
            <span>热力半径 (radius size):</span>
            <el-slider
              v-if="isHeatmapEnabled"
              v-model="radiusSize"
              :min="1"
              :max="50"
              :step="1"
              label="热力半径 (radius size)"
              show-input
              @change="handleRadiusChange"
            />
          </div>
          <div class="blur-size">
            <span>模糊程度 (blur size):</span>
            <el-slider
              v-if="isHeatmapEnabled"
              v-model="blurSize"
              :min="0"
              :max="50"
              :step="1"
              label="模糊程度 (blur size)"
              show-input
              @change="handleBlurChange"
            />
          </div>
          <!-- 热力图地图容器 -->
          <div id="heatmap" class="heatmap-map"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useMapStore } from '@/stores/mapStore'
import { use } from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { TitleComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import VChart from 'vue-echarts'

use([PieChart, CanvasRenderer, TitleComponent, LegendComponent, TooltipComponent])

const props = defineProps({
  eventList: {
    type: Array,
    default: () => [],
  },
})
const mapStore = useMapStore()
const activeTab = ref('event')
const loading = ref(true)

const typeData = computed(() => analyzeByField(props.eventList, '事件类型'))
const levelData = computed(() => analyzeByField(props.eventList, '事件等级'))

watch(
  () => props.eventList,
  (newVal) => {
    if (newVal.length > 0) {
      loading.value = false // 数据到达，关闭加载状态
    } else {
      loading.value = true // 无数据时保持加载
    }
  },
  { immediate: true }, // 立即执行一次以处理初始数据
)

const analyzeByField = (events, field) => {
  const stats = events.reduce((acc, event) => {
    const key = event[field]
    acc[key] = (acc[key] || 0) + 1
    return acc
  }, {})
  return Object.entries(stats).map(([name, value]) => ({ name, value }))
}

// 通用饼图配置
const generatePieOption = (title, data, colors) => ({
  color: colors,
  tooltip: {
    trigger: 'item',
    formatter: '{a}<br/>{b}: {c} ({d}%)',
  },
  legend: {
    orient: 'vertical',
    right: 20,
    top: 'middle',
    itemGap: 12,
    textStyle: {
      color: '#666',
    },
    formatter: function (name) {
      // 从数据中匹配对应名称的 value
      const item = data.find((item) => item.name === name)
      return `${name} | ${item?.value || 0}` // 显示名称和数值
    },
    data: data.map((item) => item.name),
  },
  series: [
    {
      name: title,
      type: 'pie',
      radius: ['45%', '70%'],
      center: ['40%', '50%'],
      data: data,
      label: {
        formatter: '{b|{b}}\n{per|{d}%}',
        // formatter: (params) => {
        //   return `${params.name} | ${params.value}\n${params.percent}%`
        // },
        rich: {
          b: {
            fontSize: 14,
            lineHeight: 20,
          },
          per: {
            color: '#999',
            fontSize: 12,
            padding: [2, 4],
          },
        },
      },
      itemStyle: {
        borderWidth: 2,
        borderColor: '#fff',
      },
    },
  ],
})

const typeOption = computed(() =>
  generatePieOption('事件类型分析', typeData.value, [
    '#5470c6',
    '#91cc75',
    '#fac858',
    '#ee6666',
    '#73c0de',
    '#3ba272',
    '#9a60b4',
  ]),
)
const levelOption = computed(() =>
  generatePieOption('事件等级分析', levelData.value, ['#73c0de', '#9a60b4', '#e690d1', '#3ba272']),
)

// 热力图逻辑
const heatmapSource = ref(null)
const heatmapLayer = ref(null)
const isHeatmapEnabled = ref(false) // 是否启用热力图
const radiusSize = ref(20) // 热力图半径
const blurSize = ref(15) // 热力图模糊程度

// 监听热力图开关的变化
watch(isHeatmapEnabled, (newValue) => {
  if (newValue) {
    initHeatmap()
  } else {
    removeHeatmap()
  }
})

// 初始化热力图
function initHeatmap() {
  if (!mapStore.mapInstance) return
  removeHeatmap()
  heatmapSource.value = new window.ol.source.Vector()
  props.eventList.forEach((event) => {
    const point = new window.ol.geom.Point(event.coordinates)
    const feature = new window.ol.Feature({
      geometry: point,
      事件等级: event.事件等级,
    })
    heatmapSource.value.addFeature(feature)
  })

  heatmapLayer.value = new window.ol.layer.Heatmap({
    source: heatmapSource.value,
    blur: blurSize.value,
    radius: radiusSize.value,
    weight: (feature) => {
      const level = feature.get('事件等级')
      return { 轻微事故: 0.3, 一般事故: 0.6, 重大事故: 0.9, 特大事故: 1.2 }[level] || 1
    },
  })
  mapStore.mapInstance.addLayer(heatmapLayer.value)
}

// 移除热力图
function removeHeatmap() {
  if (heatmapLayer.value && mapStore.mapInstance) {
    mapStore.mapInstance.removeLayer(heatmapLayer.value)
    heatmapLayer.value = null
    heatmapSource.value = null
  }
}

const handleRadiusChange = (newRadius) => {
  if (heatmapLayer.value) {
    heatmapLayer.value.setRadius(newRadius)
  }
}

const handleBlurChange = (newBlur) => {
  if (heatmapLayer.value) {
    heatmapLayer.value.setBlur(newBlur)
  }
}
</script>

<style lang="scss" scoped>
.event-info-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
  min-height: 600px;

  .event-table {
    :deep(.el-table__header th) {
      background-color: #f8f9fa;
    }
  }

  .chart-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
    gap: 24px;
    padding: 12px;

    .chart-card {
      background: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      h3 {
        margin: 0 0 20px;
        font-size: 16px;
        font-weight: 600;
      }

      .chart {
        height: 380px;
      }
    }
  }

  .heatmap-container {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
}
</style>
